package com.tanhua.sso.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.sso.enums.SexEnum;
import com.tanhua.sso.mapper.UserInfoMapper;
import com.tanhua.sso.pojo.User;
import com.tanhua.sso.pojo.UserInfo;
import com.tanhua.sso.vo.PicUploadResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

/**
 * @description:
 * @program: mytanhua
 * @author: Leon
 * @date: 2021-01-28 20:07
 **/
@Service
@SuppressWarnings("all")
public class UserInfoService {
    @Autowired
    private UserService userService;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private FaceEngineService faceEngineService;

    @Autowired
    private PicUploadService picUploadService;

    public Boolean saveUserInfo(Map<String, String> param, String token) {
//        检验token
        User user = userService.queryUserByToken(token);
        if (user == null){
            return false;
        }
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(user.getId());
        userInfo.setCity(param.get("city"));
        userInfo.setBirthday(param.get("birthday"));
        userInfo.setSex(StringUtils.equalsIgnoreCase("man",param.get("gender"))? SexEnum.MAN:SexEnum.WOMAN);
        userInfo.setNickName(param.get("nickname"));

        return userInfoMapper.insert(userInfo) == 1 ;
    }

    public Boolean saveUserLogo(MultipartFile file, String token) {
//        检验token
        User user = userService.queryUserByToken(token);
        if (user == null){
            return false;
        }

//        检验是否为人像
        try {
            boolean b = faceEngineService.checkIsPortrait(file.getBytes());
            if (!b){
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

//        将图片上传到阿里云
        PicUploadResult upload = picUploadService.upload(file);
        if ("error".equals(upload.getStatus())){
//            图片上传失败
            return false;
        }else {
//            把头像保存到用户信息表
            UserInfo userInfo = new UserInfo();
            userInfo.setLogo(upload.getName());
            QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", user.getId());
            return userInfoMapper.updateById(userInfo) == 1;
        }
    }
}
